package cn.wolfcode.mq.listener;


import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import cn.wolfcode.mq.OrderMessage;
import cn.wolfcode.mq.OrderTimeoutMessage;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@RocketMQMessageListener(
        consumerGroup = MQConstant.ORDER_CONSUMER_PENDING_TOPIC,
        topic = MQConstant.ORDER_PENDING_TOPIC
)
@Component
@Slf4j
public class OrderPendingListener implements RocketMQListener<OrderMessage> {
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMessage message) {
        log.warn("[订单信息]  收到订单信息,准备开始创建订单,消息内容为={}", JSON.toJSONString(message));
        OrderMQResult result = new OrderMQResult();
        BeanUtils.copyProperties(message,result);
        try {
            SeckillProductVo vo = seckillProductService.queryByTimeAndSeckillId(message.getTime(), message.getSeckillId());
            String orderNo = orderInfoService.doSeckill(message.getUserPhone(), vo);
            log.warn("[订单信息]  订单创建完成，订单编号为 {}", orderNo);
            //订单创建成功
            result.setOrderNo(orderNo);
            result.setCode(Result.SUCCESS_CODE);
            result.setMsg(Result.SUCCESS_MESSAGE);
            //订单消息完成之后 要同步发送 延时消息 检查其在其延时消息发送完成之后 是否  已经完成支付
            OrderTimeoutMessage timeoutMessage = new OrderTimeoutMessage();
            BeanUtils.copyProperties(message,timeoutMessage);
            timeoutMessage.setOrderNo(orderNo);
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC,MessageBuilder.withPayload(timeoutMessage).build(),1000,3);

            rocketMQTemplate.syncSend(MQConstant.ORDER_RESULT_SUCCESS_DEST,result);
        } catch (Exception e) {
            log.error("[订单消息] 订单创建失败",e);
            //订单创建失败要进行回滚事务
            result.setMsg(Result.ERROR_MESSAGE);
            result.setCode(Result.ERROR_CODE);
            orderInfoService.rollBackTran(message.getUserPhone(),message.getSeckillId(),message.getTime());
            rocketMQTemplate.syncSend(MQConstant.ORDER_RESULT_FAIL_DEST,result);
        }
    }
}
